package com.ahaoyou.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @Author LH
 * @create 2021/12/22 18:10
 */
@Component
@Slf4j
public class EsInit {

    @Autowired
    private RestHighLevelClient client;

    @PostConstruct
    public void init() {
        //获取es.json配置文件
        JSONObject esConfig = readEsJSONConfig();
        if (Objects.isNull(esConfig)) {
            log.error("读取从es.json配置文件为空");
            throw new RuntimeException("读取从es.json配置文件为空");
        }
        try {
            for (Map.Entry<String, Object> entry : esConfig.entrySet()) {
                //获取到配置文件中的索引名称
                String index = entry.getKey();
                GetIndexRequest getIndex = new GetIndexRequest(index);
                //判断索引是否已经存在
                final boolean exists = client.indices().exists(getIndex, RequestOptions.DEFAULT);
                if (!exists) {
                    //获取到索引中数据
                    JSONObject indexConfig = (JSONObject) entry.getValue();
                    JSONObject settings = indexConfig.getJSONObject("settings");
                    JSONObject mappings = indexConfig.getJSONObject("mappings");
                    //索引不存在创建索引
                    CreateIndexRequest createRequest = new CreateIndexRequest(index);
                    /**  设置索引相关参数
                     number_of_replicas 是数据备份数，如果只有一台机器，设置为0
                     number_of_shards  是数据分片数，默认为5，有时候设置为3
                     maxResultWindow  请求最大参数
                     */
                    System.out.println(settings);
                    createRequest.settings(Settings.builder()
                            .put("index.number_of_shards", settings.getString("shards"))
                            .put("index.number_of_replicas", settings.getString("replicas"))
                            .put("index.max_result_window", settings.getString("maxResultWindow"))
                    );
                    //设置字段名称字段类型
                    createRequest.mapping(mappings);
                    //创建索引
                    CreateIndexResponse indexResponse = client.indices().create(createRequest, RequestOptions.DEFAULT);
                    log.warn("创建索引结果:{}", indexResponse.isAcknowledged());
                } else {
                    log.warn("es中已经存在名为：{}的索引", index);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建索引出现异常", e);
        }
    }

    //读取es.json文件
    private JSONObject readEsJSONConfig() {
        try {
            ClassPathResource resource = new ClassPathResource("es.json");
            if (resource.exists()) {
                String data = IoUtil.read(resource.getInputStream(), CharsetUtil.CHARSET_UTF_8);
                return JSONObject.parseObject(data);
            }
        } catch (Exception e) {
            log.error("读取classpath下的es.json出现异常", e);
        }
        return null;
    }
}
